<template>
  <!-- 省市区 （高德版）-->
  <el-cascader :options="dataArea" :props="props" v-model="area" @change="onChange" clearable></el-cascader>
</template>
<script>
export default {
  props: {
    //是否可以选择一级
    checkStrictly: {
      type: Boolean,
      default: false
    },
    //格式[{name:"重庆",adcode:"100122"}]
    value: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  computed: {
    //高德数据源
    dataArea() {
      return this.$store.state.areaArray;
    }
  },
  data() {
    return {
      area: [],
      props: {
        value: "adcode",
        label: "name",
        children: "districts",
        checkStrictly: this.checkStrictly
      }
    };
  },
  created() {
    let th = this;
  },
  methods: {
    onChange(e) {
      let th = this;
      let resultArr = [];
      let dataArea = th.dataArea;
      let fn = function(arr, adcode) {
        let d = arr.find(el => {
          return el.adcode == adcode;
        });
        if (d) {
          resultArr.push({
            name: d.name,
            adcode: adcode
          });
          dataArea = d.districts;
        }
      };
      th.area.forEach(item => {
        fn(dataArea, item);
      });
      th.$emit("input", resultArr);
    },
    //加入默认值
    addDefault() {
      let th = this;
      th.area = th.value.map(el => {
        return el.adcode + "";
      }); 
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler: function() {
        let th = this;
        th.addDefault();
      }
    }
  }
};
</script>